import axios from 'axios'
import store from '@/store'
import { Message } from 'element-ui'
import { getToken, getRequestToken } from '@/utils/auth'

import { authUrl } from '@/api/platform/auth'

// create an axios instance
const service = axios.create({
  baseURL: process.env.VUE_APP_BASE_API, // url = base url + request url
  // withCredentials: true, // send cookies when cross-domain requests
  timeout: 10000 // request timeout 10s
})

// request interceptor
service.interceptors.request.use(
  async config => {
    // 添加公用头信息
    // config.headers['Common-Header'] = 1

    // do something before request is sent
    let accessToken = getToken()
    const refreshToken = getToken(true)

    if (accessToken) {
      // Authorization 前后端统一的认证头
      config.headers['Authorization'] = getRequestToken()
    } else {
      if (refreshToken && authUrl !== config.url) {
        await store.dispatch('user/refreshToken')
        accessToken = getToken()

        if (!accessToken) {
          routeLogin()
          return
        }

        // eslint-disable-next-line require-atomic-updates
        config.headers['Authorization'] = getRequestToken()
      } else {
        return config
      }
    }
    return config
  },
  error => {
    // do something with request error
    console.log(error) // for debug
    return Promise.reject(error)
  }
)

// response interceptor
service.interceptors.response.use(
  /**
   * If you want to get http information such as headers or status
   * Please return  response => response
  */

  /**
   * Determine the request status by custom code
   * Here is just an example
   * You can also judge the status by HTTP Status Code
   */
  response => {
    const res = response.data

    // if the custom code is not 200, it is judged as an error.
    if (res.code !== '200') {
      message(res)
      return Promise.reject(new Error(res.message || 'Error'))
    } else {
      return res
    }
  },
  error => {
    const res = error.response.data
    message(res)

    return Promise.reject(error)
  }
)

function routeLogin() {
  this.$router.push({
    path: '/login'
  })
}

function message(res) {
  const code = res.code
  const message = res.message

  // 第三方服务错误
  if (code === 'C100001') {
    Message({
      message: JSON.parse(message).message || 'Error',
      type: 'error',
      duration: 3 * 1000
    })
  } else {
    Message({
      message: res.message || 'Error',
      type: 'error',
      duration: 3 * 1000
    })
  }
}

export default service
